// pages/notice/projectTeam/interactiveQuestionAndAnswer/interactiveQuestionAndAnswer.js
import throttle from '../../../../utils/throttle.js';
import { giveLikeApi } from '../../../../utils/tools.js';
import Http from '../../../../utils/http.js';
const http = new Http();
const app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        // id: '35115ed4dbd946198d8051918297436c',
        id: '', //问题Iduid
        review: '', //审核字段
        authority: '', //身份权限
        uid: '',
        createuid: '', //创建人uid
        projectauthority: '',
        pjteamname: '',
        answerId: '', //回答id
        imageArr: [],
        imageArrOfThree: [],
        // 问题描述是否折叠
        fold: false,
        // 更多操作
        show: false,
        actions: [
            {
                name: '设为优秀答案',
                color: '#333333',
                className: 'select-choice',
            },
            {
                name: '编辑',
                color: '#333333',
                className: 'select-edit',
            },
            {
                name: '删除',
                color: '#ff455e',
                className: 'select-delete',
            },
        ],
        //问题内容
        projectQuestion: {},
        // 回答
        projectAnswerList: [],
        toView: '', //跳转留言id
        commentTop: 101,
        commentInfo: false,
    },
    // 查看他人主页
    jumpOthersPage(e) {
        if (e.currentTarget.dataset.anonymousflg != '01') {
            wx.navigateTo({
                url: `/functionPage/pages/othersHomePage/othersHomePage?uid=${e.currentTarget.dataset.uid}`,
            });
        }
    },
    onLoad(option) {
        this.setData(
            {
                id: option.id,
                authority: app.globalData.authority,
                uid: app.globalData.uid,
                review: option.review || '',
            },
            () => {
                this.getQuestionDetail();
            }
        );
    },
    onShow() {
        // 修改导航栏颜色
        wx.setNavigationBarColor({
            frontColor: '#000000',
            backgroundColor: '#ffffff',
            animation: {
                duration: 300,
                timingFunc: 'easeIn',
            },
        });
    },
    //点赞问题
    giveLike(e) {
        let _that = this;
        let content = e.currentTarget.dataset.content;
        let praisecnt = 'projectQuestion.praisecnt';
        let praiseflg = 'projectQuestion.praiseflg';
        _that.setData({
            [praisecnt]:
                content.praiseflg == '00'
                    ? content.praisecnt + 1
                    : content.praisecnt - 1,
            [praiseflg]: content.praiseflg == '00' ? '01' : '00',
        });
        giveLikeApi('10', content.id, _that.data.projectQuestion.praiseflg);
    },
    //点赞回答
    giveLikeAnswer(e) {
        let _that = this;
        let content =
            _that.data.projectAnswerList[e.currentTarget.dataset.index];
        let praisecnt =
            'projectAnswerList[' +
            e.currentTarget.dataset.index +
            '].praisecnt';
        let praiseflg =
            'projectAnswerList[' +
            e.currentTarget.dataset.index +
            '].praiseflg';
        _that.setData({
            [praisecnt]:
                content.praiseflg == '00'
                    ? content.praisecnt + 1
                    : content.praisecnt - 1,

            [praiseflg]: content.praiseflg == '00' ? '01' : '00',
        });
        giveLikeApi(
            '11',
            content.id,
            _that.data.projectAnswerList[e.currentTarget.dataset.index]
                .praiseflg
        );
    },
    //点击评论跳转
    // scrollTopFun(e) {
    //     let query = wx.createSelectorQuery()
    //     query.select('#comment').boundingClientRect((rect) => {
    //         this.setData({
    //             commentTop: rect.top
    //         })
    //     }).exec()
    // },
    //评论
    jumpOrRemark() {
        let _that = this;
        if (_that.data.commentTop > 100) {
            _that.setData({
                toView: 'comment',
                commentTop: 0,
            });
        } else {
            wx.showToast({
                title: '该功能暂未开放',
                icon: 'none', //如果要纯文本，不要icon，将值设为'none'
                duration: 1500,
            });
        }
    },
    // 预览图片
    previewImage(e) {
        let index = e.target.dataset.index;
        wx.previewImage({
            current: this.data.imageArr[index],
            urls: this.data.imageArr,
        });
    },
    // 预览回答图片
    previewAnswerImage(e) {
        let index = e.target.dataset.index;
        let imgarr = e.target.dataset.imgarr;
        wx.previewImage({
            current: imgarr[index],
            urls: imgarr,
        });
    },
    // 预览单图
    previewSingleImage(e) {
        let url = e.currentTarget.dataset.url;
        wx.previewImage({
            current: url,
            urls: [url],
        });
    },

    // 展开全部
    unfold() {
        this.setData({
            fold: false,
        });
    },

    // 操作答案
    edit(e) {
        // 修改导航栏颜色
        wx.setNavigationBarColor({
            frontColor: '#000000',
            backgroundColor: '#484848',
            animation: {
                duration: 300,
                timingFunc: 'easeIn',
            },
        });

        let { excellentflg } = e.currentTarget.dataset;
        if (
            app.globalData.authority == '00' ||
            app.globalData.authority == '01' ||
            this.data.projectauthority == '02'
        ) {
            if (excellentflg === '00') {
                this.setData({
                    actions: [
                        {
                            name: '设为优秀答案',
                            color: '#333333',
                            className: 'select-choice',
                        },
                        {
                            name: '编辑',
                            color: '#333333',
                            className: 'select-edit',
                        },
                        {
                            name: '删除',
                            color: '#ff455e',
                            className: 'select-delete',
                        },
                    ],
                });
            } else {
                this.setData({
                    actions: [
                        {
                            name: '取消优秀答案',
                            color: '#333333',
                            className: 'select-choice-cancel',
                        },
                        {
                            name: '编辑',
                            color: '#333333',
                            className: 'select-edit',
                        },
                        {
                            name: '删除',
                            color: '#ff455e',
                            className: 'select-delete',
                        },
                    ],
                });
            }
        } else {
            this.setData({
                actions: [
                    {
                        name: '编辑',
                        color: '#333333',
                        className: 'select-edit',
                    },
                    {
                        name: '删除',
                        color: '#ff455e',
                        className: 'select-delete',
                    },
                ],
            });
        }
        this.setData({
            show: true,
            answerId: e.currentTarget.dataset.answerid,
        });
    },

    // 取消编辑
    onCancel() {
        // 修改导航栏颜色
        wx.setNavigationBarColor({
            frontColor: '#000000',
            backgroundColor: '#ffffff',
            animation: {
                duration: 300,
                timingFunc: 'easeIn',
            },
        });
        this.setData({
            show: false,
        });
    },

    // 选中后
    onSelect(e) {
        let _that = this;
        if (e.detail.className == 'select-delete') {
            wx.showModal({
                title: '提示：',
                content: '确认要删除这条回答吗？',
                success: function (res) {
                    if (res.confirm) {
                        //删除回答
                        wx.request({
                            url:
                                app.globalData.rootPath +
                                `cjMap/deleteProjectAnswer?authId=${app.globalData.authId}&id=${_that.data.answerId}`,
                            method: 'GET',
                            header: {
                                'content-type': 'application/json',
                            },
                            success: function (res) {
                                _that.getAnswerDetail();
                                // 刷新上一个页面
                                let pages = getCurrentPages();
                                let prevPage = pages[pages.length - 2];
                                let prevPage2 = pages[pages.length - 3];
                                if (
                                    typeof prevPage.refreshQuestion ==
                                    'function'
                                ) {
                                    prevPage.refreshQuestion();
                                }
                                if (
                                    typeof prevPage2.refreshQuestion &&
                                    typeof prevPage2.refreshQuestion ==
                                        'function'
                                ) {
                                    prevPage2.refreshQuestion();
                                }
                            },
                        });
                    } else {
                        console.log('点击取消回调');
                    }
                },
            });
        } else if (e.detail.className == 'select-choice') {
            //设为优秀回答
            wx.request({
                url:
                    app.globalData.rootPath +
                    `cjMap/editProjectAnswer?authId=${app.globalData.authId}`,
                method: 'POST',
                header: {
                    'content-type': 'application/json',
                },
                data: {
                    delflg: '00', //删除标志 00未删除 01已删除 02待审核10草稿
                    excellentflg: '01', //00 普通答案 01 优秀答案
                    pjquestionid: _that.data.id, //问题ID
                    id: _that.data.answerId, //回答id
                },
                success: function (res) {
                    _that.getAnswerDetail();
                },
            });
        } else if (e.detail.className == 'select-edit') {
            wx.navigateTo({
                url: `../../../../releasePage/pages/publishAnswer/publishAnswer?id=${_that.data.id}&answerId=${_that.data.answerId}`,
            });
        } else if (e.detail.className == 'select-choice-cancel') {
            //取消优秀回答
            wx.request({
                url:
                    app.globalData.rootPath +
                    `cjMap/editProjectAnswer?authId=${app.globalData.authId}`,
                method: 'POST',
                header: {
                    'content-type': 'application/json',
                },
                data: {
                    delflg: '00', //删除标志 00未删除 01已删除 02待审核10草稿
                    excellentflg: '00', //00 普通答案 01 优秀答案
                    pjquestionid: _that.data.id, //问题ID
                    id: _that.data.answerId, //回答id
                },
                success: function (res) {
                    _that.getAnswerDetail();
                },
            });
        }
        _that.onCancel();
    },

    changeNav: throttle((e) => {
        let { nav } = e.currentTarget.dataset;
        wx.navigateTo({
            url: nav,
        });
    }, 200),
    //获取问题、回答详情
    getQuestionDetail() {
        let _that = this;
        http.getRequest(
            `cjMap/getProjectQuestionDetail?authId=${app.globalData.authId}&id=${_that.data.id}`
        ).then((res) => {
            if (res.status == 0) {
                let img = [];
                let imgArr = [];
                if (res.projectQuestion.picurls) {
                    img =
                        res.projectQuestion.picurls.length > 3
                            ? res.projectQuestion.picurls.slice(0, 3)
                            : res.projectQuestion.picurls;
                    imgArr = res.projectQuestion.picurls;
                }
                res.projectQuestion.createtime = app.timeago(
                    res.projectQuestion.createtime
                );
                let temp = [];
                res.projectAnswerList.forEach((item) => {
                    item.editable =
                        app.globalData.authority == '00' ||
                        app.globalData.authority == '01' ||
                        item.createuid === app.globalData.uid;
                    item.createtime = app.timeago(item.createtime);
                    temp.push(item);
                });
                _that.setData(
                    {
                        imageArrOfThree: img,
                        imageArr: imgArr,
                        createuid: res.projectQuestion.createuid,
                        projectQuestion: res.projectQuestion,
                        projectAnswerList: temp,
                        projectauthority: res.projectQuestion.projectauthority,
                        pjteamname: res.projectQuestion.pjteamname,
                    },
                    () => {
                        // 获取问题描述块的高度
                        let query = wx.createSelectorQuery();
                        query.select('.question-describe').boundingClientRect();
                        query.exec((res) => {
                            if (res[0]) {
                                let height = res[0].height;
                                if (height > 170) {
                                    _that.setData({
                                        fold: true,
                                    });
                                }
                            }
                        });
                    }
                );
                // 文字变灰
                let pages = getCurrentPages(); //当前页面栈
                let prevPage = pages[pages.length - 2]; //上一页面
                if (typeof prevPage.handleRead == 'function') {
                    prevPage.handleQuestionRead();
                }
            }
        });
    },
    //获取回答详情（删除/设为优质回答后）
    getAnswerDetail() {
        let _that = this;
        http.getRequest(
            `cjMap/getProjectQuestionDetail?authId=${app.globalData.authId}&id=${_that.data.id}`
        ).then((res) => {
            if (res.status == 0) {
                let temp = [];
                res.projectAnswerList.forEach((item) => {
                    item.editable =
                        app.globalData.authority == '00' ||
                        app.globalData.authority == '01' ||
                        item.createuid === app.globalData.uid;
                    item.createuid === app.globalData.uid;
                    item.createtime = app.timeago(item.createtime);
                    temp.push(item);
                });
                _that.setData({
                    projectAnswerList: temp,
                });
            }
        });
    },
});
